﻿using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using Devonline.Entity;

namespace Devonline.CloudService.Xfyun.IdCard;

/// <summary>
/// 讯飞云认证参数
/// <typeparamref name="TParam">认证类型参数</typeparamref>
/// </summary>
public class AuthorizationModel<TParam> where TParam : class
{
    private readonly IAuthEndpoint _endpoint;
    public AuthorizationModel(IAuthEndpoint endpoint, TParam param)
    {
        ArgumentNullException.ThrowIfNull(endpoint.Secret);
        _endpoint = endpoint;
        AppKey = endpoint.Secret;
        CurTime = Convert.ToInt64((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds).ToString();
        Param = Convert.ToBase64String(Encoding.ASCII.GetBytes(param.ToJsonString()));
    }

    public string AppKey { get; init; }
    public string CurTime { get; init; }
    public string Param { get; init; }

    /// <summary>
    /// 计算 MD5 值
    /// </summary>
    /// <returns></returns>
    private string CalcMD5()
    {
        var checksum = AppKey + CurTime + Param;
        var bytes = Encoding.UTF8.GetBytes(checksum);
        bytes = MD5.HashData(bytes);
        return bytes.ToHexString(CHAR_HLINE).Replace(CHAR_HLINE.ToString(), string.Empty).ToLowerInvariant();
    }

    /// <summary>
    /// 添加 request headers
    /// </summary>
    /// <param name="headers"></param>
    public void AddHeaders(HttpRequestHeaders headers)
    {
        headers.Add("X-Appid", _endpoint.AppId);
        headers.Add("X-CurTime", CurTime);
        headers.Add("X-Param", Param);
        headers.Add("X-Checksum", CalcMD5());
    }
}